#include "../include/log.h"

bool Log::init(const char *fileName, int logBufSize, int splitLines, int maxQueueSize)
{
    // 异步
    if (maxQueueSize >= 1)
    {
        m_is_async = true;
        // 设置阻塞队列长度
        m_log_queue = new block_queue<std::string>(maxQueueSize);
        pthread_t tid;
        // 创建线程异步写日志
        pthread_create(&tid, NULL, flush_log_thread, NULL);
    }

    // 输出内容长度
    m_log_buf_size = logBufSize;
    m_buf = new char[m_log_buf_size];
    memset(m_buf, '\0', m_log_buf_size);

    // 日志最大行数
    m_split_lines = splitLines;

    // 获取当前时间
    time_t t = time(NULL);
    struct tm *sys_tm = localtime(&t);
    struct tm my_tm = *sys_tm;

    // 反向寻找第一个/的位置
    const char *p = strrchr(fileName, '/');
    char log_full_name[256]{0};
    // 若文件名没有/
    if (p == NULL)
        // 将时间+文件名做日志名
        snprintf(log_full_name, strlen(fileName), "%d_%02d_%02d_%s", my_tm.tm_year + 1900, my_tm.tm_mon + 1, my_tm.tm_mday, fileName);
    else
    {
        // 拷贝文件名
        strcpy(log_name, p + 1);
        // 复制路径名
        strncpy(dir_name, fileName, p - fileName + 1);
        snprintf(log_full_name, strlen(dir_name) + strlen(log_name) + 12, "%s%d_%02d_%02d_%s", dir_name, my_tm.tm_year + 1900, my_tm.tm_mon + 1, my_tm.tm_mday, log_name);
    }

    m_today = my_tm.tm_mday;
    m_fp = fopen(log_full_name, "a");
    if (m_fp == NULL)
        return false;
    return true;
}

void Log::write_log(int level, const char *format, ...)
{
    struct timeval now
    {
        0, 0
    };
    gettimeofday(&now, NULL);
    time_t t = now.tv_sec;
    struct tm *sys_tm = localtime(&t);
    struct tm my_tm = *sys_tm;
    char s[16]{0};

    switch (level)
    {
    case 0:
        strcpy(s, "[DEBUG]: ");
        break;

    case 1:
        strcpy(s, "[INFO]: ");
        break;

    case 2:
        strcpy(s, "[WARN]: ");
        break;

    case 3:
        strcpy(s, "[ERROR]: ");
        break;

    default:
        strcpy(s, "[INFO]: ");
        break;
    }

    m_mutex.lock();
    // 更新当前行数
    m_count++;
    // 日志时间不是今天/写入的行数是最大行倍数
    if (m_today != my_tm.tm_mday || m_count % m_split_lines == 0)
    {
        char new_log[256]{0};
        fflush(m_fp);
        fclose(m_fp);
        char tail[16]{0};
        // 格式化时间部分
        snprintf(tail, 16, "%d_%02d_%02d_", my_tm.tm_year + 1900, my_tm.tm_mon + 1, my_tm.tm_mday);

        // 时间不是今天
        if (m_today != my_tm.tm_mday)
        {
            // 创建今天的日志
            snprintf(new_log, strlen(log_name), "%s%s%s", dir_name, tail, log_name);
            m_today = my_tm.tm_mday;
            m_count = 0;
        }
        else
        {
            // 超过最大行，在日志名后加后缀 m_count/m_split_lines
            snprintf(new_log, strlen(log_name), "%s%s%s.%lld", dir_name, tail, log_name, m_count / m_split_lines);
        }
        m_fp = fopen(new_log, "a");
    }
    m_mutex.unlock();

    // 格式化输出
    va_list valst;
    va_start(valst, format);
    std::string log_str;
    m_mutex.lock();
    // 写入内容格式：时间+内容
    int n = snprintf(m_buf, 48, "%d-%02d-%02d %02d:%02d:%02d.%06ld %s",
                     my_tm.tm_year + 1900, my_tm.tm_mon + 1, my_tm.tm_mday,
                     my_tm.tm_hour, my_tm.tm_min, my_tm.tm_sec, now.tv_usec, s);
    // 内容格式化（返回写入字符个数）
    int m = vsnprintf(m_buf + n, m_log_buf_size - 1, format, valst);
    m_buf[n + m] = '\n';
    m_buf[n + m + 1] = '\0';
    log_str = m_buf;
    m_mutex.unlock();

    // 若异步，则将日志信息加入阻塞队列，同步则加锁写入文件
    if (m_is_async && !m_log_queue->full())
        m_log_queue->push(log_str);
    else
    {
        m_mutex.lock();
        fputs(log_str.c_str(), m_fp);
        m_mutex.unlock();
    }

    va_end(valst);
}

void Log::flush(void)
{
    m_mutex.lock();
    fflush(m_fp);
    m_mutex.unlock();
}

Log::Log()
{
    m_count = 0;
    m_is_async = false;
}

Log::~Log()
{
    if (m_fp != NULL)
        fclose(m_fp);
}

void *Log::async_write_log()
{
    std::string single_log;
    // 从队列取日志，写入文件
    while (m_log_queue->pop(single_log))
    {
        m_mutex.lock();
        fputs(single_log.c_str(), m_fp);
        m_mutex.unlock();
    }
    return NULL;
}
